//
//  NSObject+LXModelExtension.m
//  LXModelExtensionExample
//
//  Created by imera on 16/5/16.
//  Copyright © 2016年 LX. All rights reserved.
//

#import "NSObject+LXModelExtension.h"
#import "NSObject+LXProperty.h"
#import "LXProperty.h"

@implementation NSObject (LXModelExtension)

#pragma mark - 字典转模型
+ (instancetype)lx_setWithDict:(NSDictionary *)dict
{
    return [[self alloc]lx_setWithDict:dict];
}

- (instancetype)lx_setWithDict:(NSDictionary *)dict
{
    return [[self init]setWithDict:dict];
}

- (instancetype)setWithDict:(NSDictionary *)dict
{
    //获取类的所有成员属性
    NSArray *arr = [self getClassProperty];
    for (LXProperty *property in arr) {
        id value = nil;
        NSString *key = property.name;
        
        if (property.isModelObject) { //模型数据
            value = [property.modelClass lx_setWithDict:[dict valueForKey:key]];
        }else{
            value = [dict valueForKey:key];
        }
        
        if (value != nil) {
            [self setValue:value forKey:key];
        }
    }
    
    return self;
}

#pragma mark - 模型转字典
- (NSDictionary *)lx_dict
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    //获取类的所有成员属性
    NSArray *arr = [self getClassProperty];
    for (LXProperty *proprety in arr) {
        id value = nil;
        NSString *key = proprety.name;
        if (proprety.isModelObject) {
            NSObject *class = [self valueForKey:key];
            value = class.lx_dict;
        }else{
            value = [self valueForKey:key];
        }
        [dict setValue:value forKey:key];
    }
    return dict;
}

#pragma mark - 字典数组转模型数组
+ (NSArray *)lx_objectsArrayWithDictArray:(NSArray *)arr
{
    NSMutableArray *modelArr = [NSMutableArray array];
    for (NSDictionary *dict in arr) {
        [modelArr addObject:[self lx_setWithDict:dict]];
    }
    return modelArr;
}

#pragma mark - 字典转模型，多级映射
+ (instancetype)lx_objectWithMap:(NSDictionary *)dict map:(NSDictionary *)map
{
    return [[self alloc]lx_objectWithMap:dict map:map];
}

- (instancetype)lx_objectWithMap:(NSDictionary *)dict map:(NSDictionary *)map
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    
    NSArray *propertys = [self getClassProperty];
    for (LXProperty *property in propertys) {
        id key = [map objectForKey:property.name];
        if (key && [mutableDict objectForKey:key]) {
            [mutableDict setObject:[mutableDict objectForKey:key] forKey:property.name];
            [mutableDict removeObjectForKey:key];
        }
    }
    return [[self init]lx_setWithDict:mutableDict];
}

@end
